package com.elong.businesstravel.modules.home.ticket.search;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView.OnChildClickListener;

import com.android.support.jhf.dialog.CustomWaitDialog.OnKeyCancel;
import com.android.support.jhf.handlerui.HandlerPostUI;
import com.android.support.jhf.handlerui.HandlerToastUI;
import com.android.support.jhf.network.NetworkClient;
import com.android.support.jhf.network.loopj.android.http.ResponseHandlerInterface;
import com.elong.businesstravel.R;
import com.elong.businesstravel.base.baseactivity.BaseActivity;
import com.elong.businesstravel.base.utils.SaveUserOperate;
import com.elong.businesstravel.base.view.TitleNavBarView;
import com.elong.businesstravel.entitys.City;
import com.elong.businesstravel.entitys.TrainStation;
import com.elong.businesstravel.modules.home.adapter.SimpleListAdapter;
import com.elong.businesstravel.modules.home.hotel.adapter.CityAutoCompleteAdapter;
import com.elong.businesstravel.modules.home.hotel.widget.CitySearchAutoCompleteTextView;
import com.elong.businesstravel.modules.home.ticket.adapter.TrainStationAutoCompleteAdapter;
import com.elong.businesstravel.protocol.ticket.GetStationListRequest;
import com.elong.businesstravel.protocol.ticket.GetStationListResponse;

/**
 * 车站列表 flag 0起始车站，1终点车站
 * 
 * @author lenovo
 * 
 */
public class StationListActivity extends BaseActivity {

	private ListView mListView;
	private CitySearchAutoCompleteTextView mSearchAutoCompleteTextView;
	private SimpleListAdapter mSimpleListAdapter;

	/** 0起始车站，1终点车站 */
	private int mFlag = 0;
	private String mTitleString;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_station_list);

		init();
	}

	@Override
	protected void init() {

		if (null == mSavedInstanceState) {
			mFlag = getIntent().getIntExtra("flag", 0);
			mTitleString = getIntent().getStringExtra("title");
		} else {
			mFlag = mSavedInstanceState.getInt("flag");
			mTitleString = mSavedInstanceState.getString("title");
		}

		mListView = (ListView) findViewById(R.id.listView);
		mSearchAutoCompleteTextView = (CitySearchAutoCompleteTextView) findViewById(R.id.searchAutoCompleteTextView);
		mSearchAutoCompleteTextView
				.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_COMPLETE);
		initAutoComplete(mSearchAutoCompleteTextView);

		setListener();
		
		setTitleNavBar();
	}
	
	@Override
	protected void setTitleNavBar() {

		TitleNavBarView titleNavBarView = (TitleNavBarView) findViewById(R.id.titleNavBarView);
		titleNavBarView.setMessage(mTitleString);
		titleNavBarView.setTitleBackground(R.color.bg_title_dialog);
		titleNavBarView.setLeftButtonImageString(0, "取消", R.color.text_blue);
		titleNavBarView
				.setLeftButtonOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						finish();
					}
				});
		titleNavBarView.setRightButtonVisibility(View.INVISIBLE);
	}

	@Override
	protected void setListener() {
		Button searchButton = (Button) findViewById(R.id.searchButton);
		searchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				String contain = mSearchAutoCompleteTextView.getText()
						.toString();
				List<TrainStation> rawCities = mApplication.mTrainStations;
				List<TrainStation> tempCities = new ArrayList<TrainStation>();
				if (!TextUtils.isEmpty(contain)) {
					for (int i = 0; i < mApplication.mTrainStations.size(); i++) {
						if (rawCities.get(i).getStationName()
								.startsWith(contain)) {
							tempCities.add(rawCities.get(i));
						} else if (rawCities.get(i).getStationPY()
								.startsWith(contain)) {
							tempCities.add(rawCities.get(i));
						} else if (rawCities.get(i).getStationPYS()
								.startsWith(contain)) {
							tempCities.add(rawCities.get(i));
						}

					}
				}
				if (0 == tempCities.size()) {
					HandlerToastUI.getHandlerToastUI(mContext, "没有找到您输入的城市");
				} else {
					mSearchAutoCompleteTextView.showDropDown();
				}
			}
		});
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				TrainStation trainStation = mApplication.mTrainStations
						.get(arg2);
				selectCitySaveFinish(trainStation);
			}
		});
	}

	/**
	 * 初始化AutoCompleteTextView，最多显示5项提示，使 AutoCompleteTextView在一开始获得焦点时自动提示
	 * 
	 * @param field
	 *            保存在sharedPreference中的字段名
	 * @param auto
	 *            要操作的AutoCompleteTextView
	 */
	private void initAutoComplete(final AutoCompleteTextView auto) {
		showWaitDialog("正在加载请等待", new OnKeyCancel() {

			@Override
			public void onKeyCancelListener() {
				quit();
			}
		});
		new Thread(new Runnable() {

			@Override
			public void run() {
				final List<TrainStation> tempTrainStations = new ArrayList<TrainStation>();
				tempTrainStations.addAll(mApplication.mTrainStations);

				final List<String> strings = new ArrayList<String>();
				for (int i = 0; i < mApplication.mTrainStations.size(); i++) {
					strings.add(mApplication.mTrainStations.get(i)
							.getStationName());
				}

				HandlerPostUI.getHandlerPostUI(new Runnable() {

					@Override
					public void run() {

						mSimpleListAdapter = new SimpleListAdapter(mContext,
								strings, "");
						mListView.setAdapter(mSimpleListAdapter);

						final TrainStationAutoCompleteAdapter trainStationAutoCompleteAdapter = new TrainStationAutoCompleteAdapter(
								mContext, tempTrainStations,
								mApplication.mTrainStations);
						auto.setAdapter(trainStationAutoCompleteAdapter);
						// auto.setDropDownHeight(350);
						// auto.setDropDownVerticalOffset(5);
						auto.setThreshold(1);
						auto.setOnFocusChangeListener(new OnFocusChangeListener() {
							@Override
							public void onFocusChange(View v, boolean hasFocus) {
								// AutoCompleteTextView view =
								// (AutoCompleteTextView) v;
								// if (hasFocus) {
								// view.showDropDown();
								// }
							}
						});
						auto.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								TrainStation trainStation = trainStationAutoCompleteAdapter
										.getTrainStationByIndex(arg2);
								selectCitySaveFinish(trainStation);
							}
						});
						hideWaitDialog();
					}
				});

			}
		}).start();

	}

	private void quit() {
		finish();
		overridePendingTransition(R.anim.activity_alpha_fixed,
				R.anim.activity_top_bottom_exit_anim_translate);
	}

	/**
	 * 选中城市保存退出
	 * 
	 * @param city
	 */
	private void selectCitySaveFinish(TrainStation trainStation) {
		if (0 == mFlag) {
			SaveUserOperate.setStartTrainStation(mContext, trainStation);
		} else if (1 == mFlag) {
			SaveUserOperate.setEndTrainStation(mContext, trainStation);
		}

		Intent intent = new Intent();
		intent.putExtra("trainStation", trainStation);
		setResult(RESULT_OK, intent);
		quit();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			quit();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putInt("flag", mFlag);
		outState.putString("title", mTitleString);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		if (null != savedInstanceState) {
			mFlag = savedInstanceState.getInt("flag");
			mTitleString = savedInstanceState.getString("title");
		}
	}

}
